package com.yhx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhx.iservice.IPermissionService;
import com.yhx.mapper.PermissionMapper;
import com.yhx.pojo.Permission;
import com.yhx.utils.MessageConstant;
import com.yhx.utils.PageResult;
import com.yhx.utils.QueryPageBean;
import com.yhx.utils.Result;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Resource
    private PermissionMapper permissionMapper;
    @Override
    public PageResult listpage(QueryPageBean queryPageBean) {
        QueryWrapper<Permission> queryWapper = new QueryWrapper<>();
        String queryString = queryPageBean.getQueryString();
        if(queryString!=null&&queryString.length()>0){
            queryWapper.like("name", queryString)
                    .or().like("keyword", queryString);
        }
        //创建一个分页对象
        Page<Permission> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //查询
        Page<Permission> permission = permissionMapper.selectPage(page, queryWapper);
        //返回查询结果
        return new PageResult(permission.getTotal(), permission.getRecords());
    }

    @Override
    public Result save(Permission permission) {
        int insert = permissionMapper.insert(permission);
        if(insert>0){
            return new Result(true, MessageConstant.ADD_PERMISSION_SUCCESS);
        }
        return new Result(false,MessageConstant.ADD_PERMISSION_FAIL);
    }

    @Override
    public Result getByid(int id) {
        Permission permission = permissionMapper.selectById(id);
        if(permission!=null){
            return new Result(true, MessageConstant.EDIT_PERMISSION_SUCCESS,permission);
        }
        return new Result(false, MessageConstant.EDIT_PERMISSION_FAIL);
    }

    @Override
    public Result update(Permission permission) {
        int i = permissionMapper.updateById(permission);
        if (i>0){
           return new Result(true, MessageConstant.EDIT_PERMISSION_SUCCESS);
        }
        return new Result(false, MessageConstant.EDIT_PERMISSION_FAIL);
    }

    @Override
    public Result delete(Integer[] ids) {
        List<Integer> integers = Arrays.asList(ids);
        int i = permissionMapper.deleteBatchIds(integers);
        if(i>0){
            return new Result(true, MessageConstant.DELETE_PERMISSION_SUCCESS);
        }
        return new Result(true, MessageConstant.DELETE_PERMISSION_FAIL);
    }

    @Override
    public List<Permission> list() {
        List<Permission> permissions = permissionMapper.selectList(null);
        return permissions;
    }

    @Override
    public List<Permission> listByUserId(int userId) {
        return permissionMapper.listByUserId(userId);
    }
}
